import {useState} from 'react';
import {PaymentInfo, PaymentOrder, UpdateOrderInfo} from '../types/order';
import {
  coinCalculatorQuery,
  selectUniwebOrder,
  updateOrder,
} from '../api/backend';

export function usePayment() {
  const [orderLoading, setOrderLoading] = useState<boolean>(false);
  const [orderInfo, setOrderInfo] = useState<PaymentOrder>();

  const getOrderInfoById = async (orderId: string) => {
    setOrderLoading(true);
    const orderInfo = await selectUniwebOrder(orderId);
    setOrderInfo(orderInfo == null ? undefined : orderInfo);
    setOrderLoading(false);
  };

  const getPaymentInfo = async (
    orderId: string,
    tokenSymbol: string,
    tokenDecimals: number,
    tokenAddress?: string,
  ): Promise<PaymentInfo | null> => {
    const paymentInfo = await coinCalculatorQuery(
      tokenSymbol,
      orderId,
      tokenDecimals,
    );

    return paymentInfo;
  };

  const updateOrderPaymentInfo = async (params: UpdateOrderInfo) => {
    return await updateOrder(params);
  };

  return {
    orderLoading,
    orderInfo,
    getOrderInfoById,
    getPaymentInfo,
    updateOrderPaymentInfo,
  };
}
